// 不支持写模式的数据源类型
var noSupportWMDbType = ["2","3","4","5","9"];
// 非关系型数据库的数据源类型
var noSupportSQL = ["7","9"];
// 不支持查询列字段的数据源类型
var noSupportTableField = ["7", "9"];
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'dataworks/sync/list',
        datatype: "json",
        mtype: "POST",
        colModel: [
            {name: 'id', hidden: true}, {name: 'sourceDb', hidden: true},
            {name: 'sourceTable', hidden: true}, {name: 'sourceDbType', hidden: true},
            {name: 'targetDb', hidden: true}, {name: 'targetDbType', hidden: true},
            {name: 'targetTable', hidden: true}, {name: 'writeMode', hidden: true},
            {label: '工作名称', name: 'name', index: 'name',sort:false, minColWidth: 100},
            {label: '调度任务', name: 'jobinfoName',sort:false,search: false, minColWidth: 100},
            {label: '创建时间', name: 'createTime', index: 'create_time', hidden: true}
        ],
        viewrecords: true,
        height: 'auto',
        width: 315,
        rowNum: 10,
        autowidth: false,
        //width: document.body.clientWidth,根据body的宽度使用这个请注释掉autowidth:true
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader: {
            root: "data.data",
            page: "data.pageNum",
            total: "data.pages",
            records: "data.recordCounts"
        },
        prmNames: {
            page: "page",
            rows: "limit"
        },
        postData:{'spaceId': getCookie("user_space_id")},
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        },
        ondblClickRow: function (row) {
            var rowData = $('#jqGrid').jqGrid('getRowData', row);
            globalAjaxLodingFlag = false;
            var index = loading();
            setTimeout(function(){loadSync(rowData.id);closeLoading(index)},1000);
            globalAjaxLodingFlag = true;
        }
    });
    $("#jqGrid").filterToolbar({}).jqGrid('navGrid', "#jqGridPager", {//刷新按钮
        refresh: true,
        edit: false, del: false, search: false, add: false, view: false
    });
    vm.loadSpace();
});
function loadSync(syncId){
    vm.nextStep("sync_step_1");
    vm.getInfo(syncId);

    vm.changeSourceDbType(null);
    vm.changeSourceDb(null);
    vm.changeSourceTable(null);
    vm.changeTargetDbType(null);
    vm.changeTargetDb(null);
    vm.changeTargetTable(null);
}
// 验证重复元素，有重复返回true；否则返回false
function checkArr(a) {
    var tmp = {};
    for(var i=0;i<a.length;i++){
        if(tmp[a[i].name] == "1"){
            return true;
        }else{
            tmp[a[i].name] = "1";
        }
    }
    return false;
}
var vm = new Vue({
    el: '#rrapp',
    data: {
        triggerStatusEnable: true,
        title: null,
        dbTypeList: [],
        sourceDbList: [],//来源库
        targetDbList: [],//目标库
        sourceTableList: [],//来源表
        targetTableList: [],//目标表
        sourceFieldList: [],//来源字段映射
        targetFieldList: [],//目标字段映射
        showList: true,
        showJobInfoAdd: false,
        showSyncRate: false,
        showSyncRecord: false,
        showQuerySql: false,
        showWriteMode: false,
        showSourceField: false,
        showTargetField: false,
        sync_step_1: false,
        sync_step_2: false,
        sync_step_3: false,
        spaceList: [],
        sync: {
            sourceDbType: null,
            targetDbType: null,
            sourceDb: null,
            targetDb: null,
            sourceTable: null,
            targetTable: null,
            sourceField: [],//数据库保存来源字段映射
            targetField: [],//数据库保存目标字段映射
            syncNum: -1,
            syncRate: -1,
            syncRecord: -1,
            querySql: null,
            sourceFieldStr: "",//来源字段映射
            sourceFieldStrOld: "",//来源字段映射
            targetFieldStr: "",//目标字段映射
            targetFieldStrOld: ""//目标字段映射
        },
        jobinfo: {
            triggerStatus: 0,
            addressList: null,
            addressType: 0,
            executorHandler: 'executorJobHandler',
            scheduleConf: '0 0 1 * * ?'
        },
        // 个性化数据源模块
        diySourceShowMongo: false,
        diyTargetShowMongo: false,
        diyTargetShowHive: false,
        diySourceShowHive: false,
        diyTargetShowHbase: false,
        diySourceShowHbase: false
    },
    methods: {
        query: function () {
            vm.reload();
        },
        loadSpace: function(){
            $.ajax({
                type: "POST",
                url: baseURL + "workspace/space/list",
                contentType: "application/json",
                header: {limit: 100000},
                data: {},
                success: function(r){
                    if(r.code === 0){
                        var select = $("#sycnLayer").find("select");
                        vm.spaceList = r.data.data;
                        $.each(r.data.data, function(index, item){
                            select.append("<option value='" + item.id + "'>" + item.name + "</option>");
                        });
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
        },
        add: function () {
            $("#sycnLayer").find("input[name=name]").val("");
            var select = $("#sycnLayer").find("select").val(getCookie("user_space_id"));
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "新增离线同步工作",
                area: ['400px', '250px'],
                shadeClose: false,
                content: jQuery("#sycnLayer"),
                btn: ['保存', '取消'],
                btn1: function (index) {
                    layer.close(index);
                    vm.sync = {};
                    var name = $("#sycnLayer").find("input[name=name]").val();
                    var spaceId = $("#sycnLayer").find("select").val();
                    $.ajax({
                        type: "POST",
                        url: baseURL + "dataworks/sync/syncSaveOrUpdate",
                        data: {name: name, spaceId: spaceId},
                        async: false,
                        success: function (r) {
                            if (r.code === 0) {
                                layer.msg("操作成功", {icon: 1});
                                vm.reload();
                                var index = loading();
                                setTimeout(function(){loadSync(r.data);closeLoading(index)},1000);
                            } else {
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        addShowQuerySql: function(event){
            var target = $(event.target).parent();
            var template = target.find("#template").clone(true);
            template.removeAttr("id");
            template.attr("name", "querySqlListDiv");
            template.show();
            target.append(template);
        },
        delShowQuerySql: function(event){
            var target = $(event.target).parent();
            var last = target.find("div[name=querySqlListDiv]").last();
            last.remove();
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.getInfo(id);
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "修改离线同步工作",
                area: ['400px', '250px'],
                shadeClose: false,
                content: jQuery("#sycnLayer"),
                btn: ['修改', '取消'],
                btn1: function (index) {
                    layer.close(index);
                    var name = $("#sycnLayer").find("input[name=name]").val();
                    var spaceId = $("#sycnLayer").find("select").val();
                    $.ajax({
                        type: "POST",
                        url: baseURL + "dataworks/sync/syncSaveOrUpdate",
                        data: {id: id,name: name, spaceId: spaceId},
                        async: false,
                        success: function (r) {
                            if (r.code === 0) {
                                layer.msg("操作成功", {icon: 1});
                                vm.reload();
                            } else {
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            });

            var select = $("#sycnLayer").find("select");
            var input = $("#sycnLayer").find("input");
            select.val(vm.sync.spaceId);
            input.val(vm.sync.name);
        },
        saveOrUpdate: function (event) {
            var url = "dataworks/sync/update";
            // 特殊处理-因为字段映射是iframe里面的
            vm.getFieldMapping();
            if(vm.sync.syncRecord == 0){
                vm.sync.syncRecord = -1;
            }
            if(vm.sync.syncRate == 0){
                vm.sync.syncRate = -1;
            }
            if(vm.sync.querySql != null && vm.sync.querySql != "" && vm.sync.querySql.length > 0){
                vm.sync.sourceTable = "";
            }
            if(vm.diyTargetShowMongo){
                vm.sync.writeMode = $("#writeModeInput").val();
            }
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.sync),
                async: false,
                success: function (r) {
                    if (r.code === 0) {
                        layer.msg("操作成功", {icon: 1});
                    } else {
                        layer.alert(r.msg);
                    }
                }
            });
        },
        executeJob: function(event){
            if(vm.sync.jobinfoId == null || vm.sync.jobinfoId == ""){
                alert("请先完成【调度配置】初始化!!!");
                return;
            }
            // 特殊处理-因为字段映射是iframe里面的
            vm.getFieldMapping();
            if(vm.diyTargetShowMongo){
                vm.sync.writeMode = $("#writeModeInput").val();
            }
            $.ajax({
                type: "POST",
                url: baseURL + "dataworks/sync/executeJob",
                contentType: "application/json",
                data: JSON.stringify(vm.sync),
                success: function (r) {
                    if (r.code == 0) {
                        if(r.data != null){
                            vm.showDetail(r.data, true);
                        }else{
                            layer.msg("操作成功", {icon: 1});
                        }
                    } else {
                        layer.alert(r.msg);
                    }
                }
            });
        },
        killJob: function(logId, callBack){
            layer.confirm( ('确定终止任务?'), {
                icon: 3,
                title: '系统提示' ,
                btn: [ '确定', '取消' ]
            }, function(index){
                layer.close(index);
                $.ajax({
                    type : 'POST',
                    url : baseURL + 'joblog/logKill',
                    data : {"id":logId},
                    dataType : "json",
                    success : function(r){
                        if (r.code == 200) {
                            layer.alert('操作成功');
                            if(callBack){
                                callBack();
                            }
                        } else {
                            layer.alert(r.msg);
                        }
                    },
                });
            });
        },
        showDetail: function(logId, isRun){
            var index = layer.open({
                type: 2,
                scrollbar: false,
                title: false,
                area: ['100%', '100%'],
                shadeClose: false,
                closeBtn: false,
                shade:0.7,
                skin: 'myskin',
                content: baseURL + 'joblog/logDetailPage?id=' + logId,
                success: function(layero, index){
                    var child = document.getElementById("layui-layer-iframe"+index).contentWindow;
                    // 初始化传递layer下标，用于iframe控制父窗口组件
                    child.initLayer(index);
                },
                btn: ['暂停刷新', '终止任务', '关闭']
                ,yes: function(index, layero){
                    var child = document.getElementById("layui-layer-iframe"+index).contentWindow;
                    var btn = $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0");
                    if(btn.html() == "暂停刷新"){
                        child.logRunStop("暂停刷新...");
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0").html("继续刷新");
                    }else{
                        child.logRunFn();
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0").html("暂停刷新");
                    }
                },btn2: function(index, layero){
                    vm.killJob(logId, function(){
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn1").hide();
                    });
                    return false;
                }
            });

            if(!isRun){
                $("body").find(".layui-layer-btn").find(".layui-layer-btn0").hide();
                $("body").find(".layui-layer-btn").find(".layui-layer-btn1").hide();
            }
        },
        executeLog: function(){
            if(!vm.sync.jobinfoId || vm.sync.jobinfoId == ""){
                layer.msg("尚未绑定调度配置无对应任务!", {icon: 1});
                return;
            }
            $.ajax({
                type: "GET",
                url: baseURL + "joblog/lastJob?xxlJobId=" + vm.sync.jobinfoId,
                contentType: "application/json",
                success: function (r) {
                    if (r.code == 0) {
                        if(r.data != null){
                            if(r.data.triggerCode == 200 && r.data.handleCode == 0){
                                vm.showDetail(r.data.id, true);
                            }else{
                                vm.showDetail(r.data.id, false);
                            }
                        }else{
                            layer.msg("暂无执行任务", {icon: 1});
                        }
                    } else {
                        layer.alert(r.msg);
                    }
                }
            });
        },
        changeSyncRate: function(event){
            var val = event.target.value;
            if(val == 1){
                vm.showSyncRate = true;
            }else{
                vm.showSyncRate = false;
                vm.sync.syncRate = -1;
            }
        },
        changeSyncRecord: function(event){
            var val = event.target.value;
            if(val == 1){
                vm.showSyncRecord = true;
            }else{
                vm.showSyncRecord = false;
                vm.sync.syncRecord = -1;
            }
        },
        del: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            var ids = [];
            ids.push(id);
            var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                if (!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "dataworks/sync/deleteBatch",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function (r) {
                            if (r.code == 0) {
                                vm.sync_step_1 = false;
                                vm.sync_step_2 = false;
                                vm.sync_step_3 = false;
                                vm.sync = {};
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            } else {
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function () {
            });
        },
        getInfo: function (id) {
            $.ajax({
                type: "GET",
                url: baseURL + "dataworks/sync/info/" + id,
                contentType: "application/json",
                dataType: 'json',
                async: false,
                success: function (r) {
                    if (r.code == 0) {
                        vm.sync = {};
                        vm.sync = r.data;
                        vm.reset();
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        reset: function(){
            // 初始化自定义数据源Show
            vm.changeDiyShow(vm.sync.sourceDbType, true);
            vm.changeDiyShow(vm.sync.targetDbType, false);

            // 主要用来做一下初始化的控件是否显示初始值等
            // 初始化是否自定义SQL
            var querySql = $("#sync_step_1").find("input[name=querySql]");
            if(vm.sync.querySql != null && vm.sync.querySql != ""){
                vm.showQuerySql = true;
                querySql.prop("checked",true);
                $("#querySqlArea").val(vm.sync.querySql);
            }else{
                vm.showQuerySql = false;
                querySql.prop("checked",false);
            }
            // 初始化第三步通道控制控件
            if(vm.sync.syncNum == null){
                vm.sync.syncNum = 1;
            }
            if(vm.sync.syncRate > 0){
                vm.showSyncRate = true;
                $("input[name=syncRate][value='1']").prop("checked", "checked");
            }else{
                vm.showSyncRate = false;
                $("input[name=syncRate][value='0']").prop("checked", "checked");
            }
            if(vm.sync.syncRecord > 0){
                vm.showSyncRecord = true;
                $("input[name=syncRecord][value='1']").prop("checked", "checked");
            }else{
                vm.showSyncRecord = false;
                $("input[name=syncRecord][value='0']").prop("checked", "checked");
            }
        },
        initDbList: function (dbType, isSource, event) {
            if (!dbType || dbType == "" || dbType == null) {
                return null;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "datasource/database/list",
                data: {type: dbType, spaceId: getCookie("user_space_id")},
                async: false,
                success: function (r) {
                    if (r.code == 0) {
                        if (isSource) {
                            vm.sourceDbList = r.data.data;
                            if (event != null) {
                                vm.sync.sourceTable = "";
                            }
                        } else {
                            vm.targetDbList = r.data.data;
                            if (event != null) {
                                vm.sync.targetTable = "";
                            }
                        }
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        changeDb: function (db, isSource) {
            if (!db || db == "" || db == null) {
                return;
            }
            $.ajax({
                type: "GET",
                url: baseURL + "datasource/database/tablesOfDb/" + db,
                async: false,
                success: function (r) {
                    if (r.code == 0) {
                        if (isSource) {
                            vm.sourceTableList = r.data;
                        } else {
                            vm.targetTableList = r.data;
                        }
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        changeTable: function(db, dbType, table, isSource, querySql){
            // 排除不支持查询列的数据源
            if($.inArray(dbType, noSupportTableField) != -1){
                if (isSource) {
                    vm.sourceFieldList = [];
                } else {
                    vm.targetFieldList = [];
                }
                return;
            }
            if ((!table && !querySql) || (table == "" && querySql == "")) {
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "datasource/database/fieldOfTable?id=" + db,
                data:{table:table, querySql: querySql},
                success: function (r) {
                    if (r.code == 0) {
                        if (isSource) {
                            if(querySql && querySql != ""){
                                if(checkArr(r.data)){
                                    alert("自定义SQL存在重复列!!!");return;
                                }
                            }
                            if(r.data.length == 0){
                                layer.msg("来源表无映射字段", {icon: 2});
                            }
                            vm.sourceFieldList = r.data;
                        } else {
                            vm.targetFieldList = r.data;
                        }
                    } else {
                        if(querySql != null){
                            alert("SQL检查异常:"+r.msg);
                        }else{
                            alert(r.msg);
                        }
                    }
                }
            });
        },
        changeSourceDbType: function (event) {
            var val = vm.sync.sourceDbType;
            if (val && val != "") {
                if (event != null) {
                    vm.sync.sourceDb = "";
                    vm.sync.sourceTable = "";
                    vm.sync.sourceField = [];
                    vm.sync.sourceFieldStr = "";
                    vm.sync.sourceFieldStrOld = "";
                    vm.sync.whereSql = "";
                    vm.sync.isObjectId = "";
                    vm.changeDiyShow(vm.sync.sourceDbType, true);
                }
                vm.sourceDbList = [];
                vm.sourceTableList = [];
                vm.sourceFieldList = [];
                vm.initDbList(val, true, event);
            }
        },
        changeTargetDbType: function (event) {
            var val = vm.sync.targetDbType;
            if (val && val != "") {
                if (event != null) {
                    vm.sync.targetDb = "";
                    vm.sync.targetTable = "";
                    vm.sync.targetField = [];
                    vm.sync.writeMode = "";
                    vm.sync.targetFieldStr = "";
                    vm.sync.targetFieldStrOld = "";
                    vm.sync.rowkeyColumn = "";
                    vm.changeDiyShow(vm.sync.targetDbType, false);
                }
                vm.targetDbList = [];
                vm.targetTableList = [];
                vm.targetFieldList = [];
                vm.initDbList(val, false, event);
            }
        },
        changeSourceDb: function (event) {
            var val = vm.sync.sourceDb;
            if (val && val != "") {
                if(event != null){
                    vm.sync.sourceTable = "";
                    vm.sync.sourceField = [];
                    vm.sync.rowkeyColumn = "";
                }
                vm.sourceTableList = [];
                vm.sourceFieldList = [];
                vm.changeDb(val, true);
            }
        },
        changeTargetDb: function (event) {
            var val = vm.sync.targetDb;
            if (val && val != "") {
                if(event != null){
                    vm.sync.targetTable = "";
                    vm.sync.targetField = [];
                }
                vm.targetTableList = [];
                vm.targetFieldList = [];
                vm.changeDb(val, false);
            }
        },
        changeSourceTable: function(event){
            var table = vm.sync.sourceTable;
            var querySql = vm.sync.querySql;
            var db = vm.sync.sourceDb;
            var dbType = vm.sync.sourceDbType;
            if (table != "" || querySql != "") {
                if(event != null){
                    vm.sync.sourceField = [];
                    vm.sync.sourceFieldStrOld = "";
                    vm.sync.sourceFieldStr = "";
                }
                vm.sourceFieldList = [];
                vm.changeTable(db, dbType,table, true, querySql);
            }
        },
        changeTargetTable: function(event){
            var table = vm.sync.targetTable;
            var db = vm.sync.targetDb;
            var dbType = vm.sync.targetDbType;
            if (table != "") {
                if(event != null){
                    vm.sync.targetField = [];
                    vm.sync.targetFieldStrOld = "";
                    vm.sync.targetFieldStr = "";
                    vm.sync.rowkeyColumn = "";
                }
                vm.targetFieldList = [];
                vm.changeTable(db, dbType, table, false);
            }
        },
        changeQuerySql: function(event){
            vm.sourceFieldList = [];
            vm.sync.sourceField = [];
            vm.sync.sourceTable = "";
            vm.sync.querySql = "";
            vm.sync.whereSql = "";
            vm.sync.splitPk = "";
            var checked = event.target.checked;
            if(checked){
                vm.showQuerySql = true;
                // 添加以下代码使光标聚焦到文本域
                this.$nextTick(function() {
                    document.getElementById('querySqlArea').focus();
                });
            }else{
                vm.showQuerySql = false;
            }
        },
        changeSourceField: function(event){
            vm.sourceFieldList = [];
            vm.sync.sourceFieldStrOld = "";
            vm.sync.sourceFieldStr = "";

            var checked = event.target.checked;
            if(checked){
                vm.showSourceField = true;
            }else{
                vm.showSourceField = false;
                vm.changeSourceTable(event);
            }
        },
        blurQuerySql: function(target){
            vm.sync.querySql = target.value;
            vm.changeSourceTable();
        },
        getFieldMapping: function(){
            var child = document.getElementById("fieldMappingIframe").contentWindow;
            if(child.vm){
                var connection = child.vm.getConnection();
                vm.sync.sourceField = connection.source;
                vm.sync.targetField = connection.target;
            }
        },
        saveOrUpdateJobInfo: function(){
            vm.convertSelectVal();
            $.ajax({
                type: "POST",
                url: baseURL + "dataworks/sync/bindJob?id="+vm.sync.id,
                contentType: "application/json",
                data: JSON.stringify(vm.jobinfo),
                success: function(r){
                    if(r.code == 0){
                        layer.msg("操作成功", {icon: 1});
                        vm.showJobInfoAdd = false;
                        vm.sync.jobinfoId = r.data;
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
        },
        jobInfoAddBack: function(){
            vm.showJobInfoAdd = false;
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        },
        nextStep: function (step) {
            if(step != "sync_step_2"){
                vm.getFieldMapping();
            }
            if(step == "sync_step_2"){
                if(vm.sync.sourceFieldStr != "" && vm.sync.sourceFieldStr != vm.sync.sourceFieldStrOld){
                    try{
                        vm.sourceFieldList = [];
                        var fieldStr = JSON.parse(vm.sync.sourceFieldStr);
                        $.each(fieldStr, function(index, item){
                            vm.sourceFieldList.push({"name": item.name,"type": item.type, "index": item.index, "value": item.value});
                        });
                        vm.sync.sourceFieldStrOld = vm.sync.sourceFieldStr;
                    }catch (e) {
                        layer.alert("来源字段列名JSON格式错误!");
                        return false;
                    }
                }else if(vm.showSourceField && vm.sync.sourceFieldStr == ""){
                    vm.sync.sourceFieldStrOld = "";
                    vm.sourceFieldList = [];
                }
                if(vm.sync.targetFieldStr != "" && vm.sync.targetFieldStr != vm.sync.targetFieldStrOld){
                    try{
                        vm.targetFieldList = [];
                        var fieldStr = JSON.parse(vm.sync.targetFieldStr);
                        $.each(fieldStr, function(index, item){
                            vm.targetFieldList.push({"name": item.name,"type": item.type, "index": item.index, "value": item.value});
                        });
                        vm.sync.targetFieldStrOld = vm.sync.targetFieldStr;
                    }catch (e) {
                        layer.alert("目标字段列名JSON格式错误!");
                        return false;
                    }
                }else if(vm.sync.targetFieldStr == "" && vm.sync.diyTargetShowHbase){
                    vm.sync.targetFieldStrOld = "";
                    vm.targetFieldList = [];
                }
                if(vm.sourceFieldList.length == 0){
                    alert("来源表没有可映射字段!!!");return;
                }else if(vm.targetFieldList.length == 0){
                    alert("目标表没有可映射字段!!!");return;
                }else{
                    $("#fieldMappingIframe").attr("src", baseURL + "modules/dataworks/filedMapping.html");
                    var domHeight = document.documentElement.clientHeight-50;
                    var columnSize = vm.sourceFieldList.length > vm.targetFieldList.length ? vm.sourceFieldList.length : vm.targetFieldList.length;
                    columnSize = (columnSize+3) * 20;
                    var height = domHeight > columnSize ? domHeight : columnSize;
                    $("#sync_step_2_div").height(height);
                    // $("#fieldMappingIframe").height(height - 39);
                }
            }
            if(step == "sync_step_3" && vm.sync.sourceField.length == 0){
                alert("请配置映射字段");
                return;
            }
            vm.sync_step_1 = false;
            vm.sync_step_2 = false;
            vm.sync_step_3 = false;
            vm[step] = true;
        },
        bindJob: function(event){
            vm.showJobInfoAdd = true;
            $("#jobInfoForm")[0].reset();
            if(vm.sync.jobinfoId == null){
                vm.title = "新增调度任务";
                $("#scheduleType").val("CRON");
                $("#jobGroup").removeAttr("disabled");
                vm.jobinfo = {triggerStatus: 0,addressType: 0, executorHandler: 'executorJobHandler',scheduleConf: '0 0 1 * * ?'};
            }else{
                $.get(baseURL + "jobinfo/loadById?id="+vm.sync.jobinfoId, function(r){
                    if(r.code == 200){
                        vm.showJobInfoAdd = true;
                        if(r.content == null){
                            vm.sync.jobinfoId = null;
                            vm.title = "新增调度任务";
                            $("#scheduleType").val("CRON");
                            $("#jobGroup").removeAttr("disabled");
                            vm.jobinfo = {triggerStatus: 0,addressType: 0, executorHandler: 'executorJobHandler',scheduleConf: '0 0 1 * * ?'};
                        }else{
                            vm.title = "编辑调度任务";
                            vm.jobinfo = r.content;
                            vm.convertSelectVal(vm.jobinfo);
                        }
                    }else{
                        alert(r.msg);
                    }
                });
            }
        },
        convertSelectVal: function(obj){
            if(!obj){
                // obj不存在则获取值绑定到vm对象
                vm.jobinfo.jobGroup = $("#jobGroup").val();
                vm.jobinfo.executorRouteStrategy = $("#executorRouteStrategy").val();
                vm.jobinfo.glueType = $("#glueType").val();
                vm.jobinfo.executorBlockStrategy = $("#executorBlockStrategy").val();
                vm.jobinfo.misfireStrategy = $("#misfireStrategy").val();
                vm.jobinfo.scheduleType = $("#scheduleType").val();
            }else{
                // obj存在则获取obj值绑定到dom对象
                $("#jobGroup").val(vm.jobinfo.jobGroup).attr("disabled","disabled");
                $("#executorRouteStrategy").val(vm.jobinfo.executorRouteStrategy);
                $("#glueType").val(vm.jobinfo.glueType);
                $("#executorBlockStrategy").val(vm.jobinfo.executorBlockStrategy);
                $("#misfireStrategy").val(vm.jobinfo.misfireStrategy);
                $("#scheduleType").val(vm.jobinfo.scheduleType).attr("disabled","disabled");
            }
        },
        changeDiyShow: function(dbType, isSource){
            if(isSource){
                vm.diySourceShowMongo = false;
                vm.diySourceShowHive = false;
                vm.diySourceShowHbase = false;
                // 重置自定义查询控件
                var querySql = $("#sync_step_1").find("input[name=querySql]");
                vm.showQuerySql = false;
                querySql.prop("checked",false);
                // 重置hive的自定义字段控件
                var diySourceField = $("#sync_step_1").find("input[name=diySourceField]");
                vm.showSourceField = false;
                diySourceField.prop("checked",false);

                if(dbType == 7){
                    vm.diySourceShowMongo = true;
                }
                if(dbType == 8){
                    vm.diySourceShowHive = true;
                }
                if(dbType == 9){
                    vm.diySourceShowHbase = true;
                    vm.showSourceField = true;
                }
                if(vm.isNoSupportTableField(vm.sync.sourceDbType)){
                    vm.sourceFieldStr = JSON.stringify(vm.sync.sourceField);
                }
            }else{
                vm.diyTargetShowMongo = false;
                vm.diyTargetShowHive = false;
                vm.diyTargetShowHbase = false;

                if(dbType == 7) {
                    vm.diyTargetShowMongo = true;
                }
                if(dbType == 8) {
                    vm.diyTargetShowHive = true;
                }
                if(dbType == 9) {
                    vm.diyTargetShowHbase = true;
                }

                // 是否回填
                if(vm.diyTargetShowMongo){
                    $("#writeModeInput").val(vm.sync.writeMode);
                }
                // 是否显示主键冲突
                if($.inArray(vm.sync.targetDbType, noSupportWMDbType) != -1){
                    vm.showWriteMode = false;
                }else{
                    vm.showWriteMode = true;
                    var obj = $("#writeModeSelect");
                    obj.html("");
                    obj.append('<option value="">无</option>');
                    // 初始化冲突策略
                    if(dbType != 8){
                        obj.append('<option value="insert">insert into(当主键/约束冲突报脏数据)</option>');
                        obj.append('<option value="update">on duplicate key update(当主键冲突update数据)</option>');
                        obj.append('<option value="replace">replace into(当主键/约束冲突先delete再insert)</option>');
                    }else{
                        var obj = $("#writeModeSelect");
                        obj.append('<option value="append">使用filename创建新文件，并保证文件名不冲突</option>');
                        obj.append('<option value="nonConflict">如果目录下有fileName前缀的文件，直接报错</option>');
                        obj.append('<option value="truncate">如果目录下有fileName前缀的文件，覆盖重写</option>');
                    }
                }
                if(vm.isNoSupportTableField(vm.sync.targetDbType)){
                    vm.targetFieldStr = JSON.stringify(vm.sync.targetField);
                }
            }


        },
        isNoSupportSQL: function(dbType){
            if($.inArray(dbType, noSupportSQL) != -1){
                return true;
            }
            return false;
        },
        isNoSupportTableField: function(dbType){
            if($.inArray(dbType, noSupportTableField) != -1){
                return true;
            }
            return false;
        },
        showSenior: function(obj, domId){
            var senior = obj.innerHTML;
            if(senior == "展开"){
                $("#"+domId).show();
                event.target.innerHTML = "隐藏";
            }else{
                $("#"+domId).hide();
                event.target.innerHTML = "展开";
            }
        }
    }
});